package middleware

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/model/admin/admin_users"
	"gitee.com/theegg/go-brick/app/model/partner/partner_admin/partner_admin_users"
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/gin-gonic/gin"
	"time"
)

// access　日志记录
func WriteLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		end := time.Now()
		runTime := end.Sub(start)

		path := c.FullPath()
		clientIP := c.ClientIP()
		method := c.Request.Method
		statusCode := c.Writer.Status()

		// 获取当前域 管理 商户
		region := "admin"
		v, ok := c.Get("c_region")
		if ok {
			region = v.(string)
		}

		msg := fmt.Sprintf("|%10s| %3d | %13v | %15s | %8s | %25s |",
			region,
			statusCode,
			runTime,
			clientIP,
			method, path)

		if region == "admin" {
			vUser, ok := c.Get("c_admin_user")
			if ok {
				adminUser := vUser.(*admin_users.AdminUsers)
				if adminUser.Id > 0 {
					msg += fmt.Sprintf(" %12s |", adminUser.Username)
				}
			}
		} else {
			vUser, ok := c.Get("c_partner_admin_user")
			if ok {
				adminUser := vUser.(*partner_admin_users.PartnerAdminUsers)
				if adminUser.Id > 0 {
					msg += fmt.Sprintf(" %12s |", adminUser.Username)
				}
			}
		}

		app.Log("access").Info(msg)
	}
}
